package com.jerome.rmi;

import com.jerome.rmi.constants.RmiConstant;
import com.jerome.rmi.util.RegistryUtil;

import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * The default remote service for dynamically registering Calculator
 * @author jerome
 * @date 2023/7/29
 */
public class RemoteDefaultImplementation extends UnicastRemoteObject implements RemoteDefault {
    /**
     * port for dynamic binding
     */
    private volatile AtomicInteger index = new AtomicInteger(0);
    /**
     * Used to obtain the created Calculator service list, which can be released in time later (not yet implemented)
     */
    private Map<String,Calculator> calculatorMap = new HashMap<String, Calculator>();

    protected RemoteDefaultImplementation() throws RemoteException {
        super();
    }

    public synchronized String registerNew() throws RemoteException, AlreadyBoundException {
        Registry registry = RegistryUtil.getRegistry();
        Calculator calculator = new CalculatorImplementation();
        String serverName = RmiConstant.SERVER_NAME+index.getAndIncrement();
        registry.bind(serverName,calculator);
        calculatorMap.put(serverName,calculator);
        return serverName;
    }

    /**
     * Sign up for a new Calculator service
     * @return Return the registered serverName
     * @author jerome
     * @date 2023/7/29 11:55
     */
    public synchronized String registerDefault() throws RemoteException, AlreadyBoundException {
        if(calculatorMap.get(RmiConstant.SERVER_NAME)==null){
            Registry registry = RegistryUtil.getRegistry();
            Calculator calculator = new CalculatorImplementation();
            String serverName = RmiConstant.SERVER_NAME;
            registry.bind(serverName,calculator);
            calculatorMap.put(serverName,calculator);
        }
        return RmiConstant.SERVER_NAME;
    }
}
